<script setup lang="ts">
import { updateUserAvatarAPI, updateUserProfileAPI } from '@/api';
import { useAreaList, useUserInfo } from '@/composable';
import type { ActionSheetAction } from 'vant';
import { showLoadingToast, showToast } from 'vant'
import { computed, onMounted, ref } from 'vue';
import b64toBlob from 'b64-to-blob';

const showSheet = ref(false) // 显示面板
const showSelectBirthday = ref(false) // 显示选择生日
const showSelectProfesstion = ref(false) // 显示选择职业
const showSelectCity = ref(false) // 显示选择城市

const { areaList } = useAreaList() // 获取省市区数据
const { userInfo } = useUserInfo() // 获取用户信息数据

let changeAvatar = false // 是否改了头像


const minDate = new Date("1980-01-01")
const maxDate = new Date("2010-01-01")
// 显示面板的数据
const actions = [
    { name: '拍照上传' },
    { name: '从相册选择' },
];
// 职业的数据
const columns = [
    { text: '软件工程师', value: '软件工程师' },
    { text: '医生', value: '医生' },
    { text: '教师', value: '教师' },
    { text: '律师', value: '律师' },
    { text: '会计师', value: '会计师' },
    { text: '销售经理', value: '销售经理' },
    { text: '市场营销专员', value: '市场营销专员' },
    { text: '建筑师', value: '建筑师' },
    { text: '护士', value: '护士' },
    { text: '机械工程师', value: '机械工程师' }
]
// 点击拍照上传或者相册选择的时候
const selectUpload = async (action: ActionSheetAction, index: number) => {
    if (index === 0) {
        const base64Str = await hdm.takePictureBase64()
        userInfo.value.avatar = base64Str
        changeAvatar = true
        // 拍照上传
    } else if (index === 1) {
        const base64Str = await hdm.selectPictureBase64()
        userInfo.value.avatar = base64Str
        changeAvatar = true
    }

}
// 选择生日的确认方法

const confirmBirthDay = (event: { selectedValues: string[] }) => {
    userInfo.value.birthday = event.selectedValues.join('-')
    showSelectBirthday.value = false
}
const confirmCity = (event: { selectedValues: string[], selectedOptions: CityItem[] }) => {
    const codeList = event.selectedValues // 所有的code
    userInfo.value.provinceCode = codeList[0] // 省的编码
    userInfo.value.cityCode = codeList[1] // 市编码
    userInfo.value.countyCode = codeList[2] // 区编码

    // 找到省的位置
    const province = event.selectedOptions.find(item => item.value === userInfo.value.provinceCode)
    // province?.text
    const city = province?.children.find(item => item.value === userInfo.value.cityCode)
    // city.text
    const county = city?.children.find(item => item.value === userInfo.value.countyCode)
    userInfo.value.fullLocation = `${province?.text}${city?.text}${county?.text}`
    showSelectCity.value = false // 关闭弹层
}
// 选择职业
const confirmProfesstion = (event: { selectedValues: string[] }) => {
    userInfo.value.profession = event.selectedValues[0]
    showSelectProfesstion.value = false // 关闭弹层
}
// 头像地址- https://www.cos.xx.png
// base64:image;xxxxx
const avatar = computed(() => {
    // 线上地址
    if (userInfo.value.avatar.startsWith("http://") || userInfo.value.avatar.startsWith("https://")) {
        return userInfo.value.avatar
    }
    // base64
    return `data:image/jpeg;base64,${userInfo.value.avatar}`

})
// 保存资料
const saveProfile = async () => {
    const instance = showLoadingToast({
        message: '保存修改中...',
        duration: 0
    })
    try {
        // 走完逻辑再关 
        if (changeAvatar) {
            // 先去修改头像
            const data = new FormData() // 空的
            // data.append("file", )
            // base64的字符串 => file对象
            // base64 => blob(File对象切片)-切成n个blob- 此时认为一个blob就是一个file
            const blob = b64toBlob(userInfo.value.avatar, 'image/jpeg')
            data.append("file", blob, Date.now() + ".jpg") // 添加到formData中
            // file => file.name
            await updateUserAvatarAPI(data)
        }
        // 调用用户资料的接口
        await updateUserProfileAPI(userInfo.value)
        hdm.updateUser() // 调用原生鸿蒙的更新
        showToast("更新用户信息成功")

    } catch (error) {

    } finally {
        instance.close() // 关闭进度条
    }


}
</script>

<template>
    <div class="profile-edit-page">
        <!-- 头像部分 -->
        <div class="avatar">
            <van-image @click="showSheet = true" round width="100" height="100" class="avatar-img" :src="avatar">
            </van-image>
            <div @click="showSheet = true" class="avatar-btn">
                <span>修改头像</span>
            </div>
        </div>

        <!-- 中间表单部分 -->
        <van-cell-group>
            <van-field label="账号" v-model="userInfo.account" readonly></van-field>
            <van-field v-model="userInfo.nickname" label="昵称" placeholder="请输入昵称"></van-field>
            <van-cell title="性别" class="gender">
                <van-radio-group :icon-size="16" v-model="userInfo.gender">
                    <van-radio name="男">男</van-radio>
                    <van-radio name="女">女</van-radio>
                </van-radio-group>
            </van-cell>
            <van-field label="生日" v-model="userInfo.birthday" readonly placeholder="请选择日期"
                @click="showSelectBirthday = true"></van-field>
            <van-field label="所在地" v-model="userInfo.fullLocation" readonly placeholder="请选择所在地"
                @click="showSelectCity = true"></van-field>
            <van-field label="职业" v-model="userInfo.profession" readonly placeholder="请选择职业"
                @click="showSelectProfesstion = true"></van-field>
        </van-cell-group>

        <div class="submit">
            <van-button @click="saveProfile" class="submit_button" round block type="primary"> 保存资料 </van-button>
        </div>

        <!-- 放置弹层面板 -->
        <!-- v-model:(活动)属性 =  -->
        <!-- <input v-model = "" />  v-model:value = ""-->
        <van-action-sheet @select="selectUpload" v-model:show="showSheet" :actions="actions" cancel-text="取消"
            close-on-click-action />
        <!-- 生日弹层 -->
        <van-popup v-model:show="showSelectBirthday" position="bottom">
            <van-date-picker @confirm="confirmBirthDay" @cancel="showSelectBirthday = false" title="选择日期"
                :min-date="minDate" :max-date="maxDate" />
        </van-popup>
        <!-- 选择职业弹层 -->
        <van-popup v-model:show="showSelectProfesstion" position="bottom">
            <!-- 职业picker -->
            <van-picker title="选择职业" :columns="columns" @confirm="confirmProfesstion"
                @cancel="showSelectProfesstion = false" />
        </van-popup>
        <!-- 选择城市 -->
        <van-popup v-model:show="showSelectCity" position="bottom">
            <!-- 城市选择 -->
            <van-area :area-list="areaList" title="选择城市" @confirm="confirmCity"
                @cancel="showSelectCity = false"></van-area>
        </van-popup>

    </div>
</template>

<style lang="css" scoped>
.avatar {
    padding: 30px;
    text-align: center;
    background-color: var(--mk-white);
}

.submit_button {
    background-color: var(--mk-black);
    border-color: var(--mk-black);
}

.avatar-img {
    box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
    color: var(--mk-linear_end);
    margin-top: 10px;
}

/* ::v-deep 通过深度选择器修改组件库的样式 */
.gender ::v-deep(.van-cell__title) {
    width: 100px;
    flex: none;
}

.van-radio-group {
    display: flex;
    justify-content: space-between;
    height: 36px;
    width: 180px;
}

.submit {
    padding: 16px;
}
</style>
